<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<%@ page errorPage="/pageError.jsp"%>
<%@ page
	import="csc.traning.wpsj.servlet.lessons.*, csc.traning.wpsj.dao.*;"%>
<%
	Cookie userName = CookieUtilities.getCookie(request, "userName");
	Cookie password = CookieUtilities.getCookie(request, "password");
	if (userName != null && password != null) {
		User user = UserDB.getUser(userName.getValue(),
				password.getValue());
		if (user != null) {
			// Set to remember password in Cookie
			userName.setMaxAge(3600);
			response.addCookie(userName);

			userName.setMaxAge(60 * 60);
			response.addCookie(userName);

			String countString = CookieUtilities.getCookieValue(
					request, "accessCount", "1");
			int count = 1;
			try {
				count = Integer.parseInt(countString);
			} catch (NumberFormatException nfe) {
			}

			response.addCookie(new Cookie("accessCount", String
					.valueOf(count + 1)));
			
			session.setAttribute("user", user);

			// Keep trach list of users are online
			Counter.add(user.getUserName());

			// add the numOfOnline to application scope
			session.setAttribute("numOfOnline", Counter.size());

			String navPage = "view-employees";
			if (!user.getRole().equals("admin")) {
				navPage = "pages/file_management.jsp";
			}
			RequestDispatcher dispatcher = request
					.getRequestDispatcher(navPage);
			dispatcher.forward(request, response);
		}
	} else {
		User user = (User) session.getAttribute("user");
		if (user != null) {
			String navPage = "view-employees";
			if (!user.getRole().equals("admin")) {
				navPage = "pages/file_management.jsp";
			}
			RequestDispatcher dispatcher = request
					.getRequestDispatcher(navPage);
			dispatcher.forward(request, response);
		}
	}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Logon</title>
</head>
<body>
	<%
		if (request.getAttribute("message") != null) {
	%>
	<span style="color: red;"><%=request.getAttribute("message")%> </span>
	<%
		}
	%>
	<fieldset style="width: 400px;">

		<legend>
			Login Form - <b>Number of login successfully <%=CookieUtilities.getCookieValue(request, "accessCount",
					"1")%></b>
		</legend>
		<div style="clear: both; text-align: right;">
			<a href="pages/profile_register.jsp"> Register and Login </a>
		</div>
		<form action="logon" method="post">
			<table align="left" width="200px">
				<tr>
					<td>Username:</td>
					<%
						//session.invalidate();
					%>
					<td><input name="userName" type="text" value="" /></td>

				</tr>
				<tr>
					<td>Password:</td>
					<td><input name="password" type="password" value="" /></td>

				</tr>

				<tr align="center">
					<td colspan="2"><br />
					<input type="submit" value="Submit" /> <input name="rememberme"
						type="checkbox" value="yes" />Remember me.</td>


				</tr>
			</table>


		</form>
	</fieldset>

</body>
</html>